<?php
require '../data/data.php';

session_start();

$username = isset($_POST['username'])?htmlspecialchars($_POST['username']):'';
$password = isset($_POST['password'])?htmlspecialchars($_POST['password']):'';
$code = isset($_POST['code'])?htmlspecialchars($_POST['code']):'';

$hasError = false;
$errorBag = ['username' => '','password' => '','code' => ''];

//判断用户是否勾选了记住我
$rememberMe = false;
if (isset($_POST['remember-me']) && $_POST['remember-me'] == 1) {
	$rememberMe = true;
}

$sql = 'select id,user_name,password from users where user_name=?';
$data = query($sql,[$username]);

if (trim($username) == '') {
	$hasError = true;
	$errorBag['username'] = '用户名不能为空';
}elseif (strlen($password) < 6) {
	$hasError = true;
	$errorBag['password'] = '密码必须大于6位';
}elseif (trim($code) == '') {
	$hasError = true;
	$errorBag['code'] = '验证码不能为空';
}elseif ($code !== $_SESSION['code']) {
	$hasError = true;
	$errorBag['code'] = '验证码错误';
}elseif (count($data)>0) {
	$user = $data[0];
	if (password_verify($password,$user['password'])) {
		$ip = $_SERVER['REMOTE_ADDR'];
        if ($rememberMe === true) {
		  $tmp = md5($user['id'].time().mt_rand());
		  $rememberToken = md5(substr($tmp,3,16));

		  $salt = hash('sha256', uniqid() . mt_rand());
          // 加密自动登录令牌，要存入数据库
		  $seToken = hash('sha256', $rememberToken . $salt);
		  // 把记住我的令牌通过一次性session信息发送到要重定向的页面去发送cookie
		  $_SESSION['remember-token'] = $rememberToken;
		  // 把remember-token与salt写入数据库users表
		  $sql = 'update users set last_login=now(),last_login_ip=?,remember_token=?,token_salt=? where id=?';
		  $args = [$ip,$seToken,$salt,$user['id']];
		}else{
		  $sql = 'update users set last_login=now(),last_login_ip=? where id=?';
		  $args = [$ip,$user['id']];
        }
		execute($sql,$args);
		$_SESSION['user'] = $user;
		header('Location:../public/index.php');
		return;
	}else $errorBag['password'] = '密码错误';
}else $errorBag['username'] = '用户名不存在';

if ($hasError) {
	$inputBag['username'] = $username;
	$_SESSION['has_error'] = $hasError;
	$_SESSION['input_bag'] = $inputBag;
	$_SESSION['error_bag'] = $errorBag;
	header('Location:../public/signin.php');
}